package com.GLM.Viewer.Circle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Friends.FriendsGroupDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class CircleInviteFriendsActivity extends Activity{
	private final static int FRIENDLIST_LOADING = 111;
	private final static int FRIENDLIST_LONDED = 222;
	private ListView mFriendsList;
	private SimpleAdapter mFriendsAdapter;
	private List<Map<String, Object>> mFriendsItems = new ArrayList<Map<String, Object>>();
	private String[] friendsItemKeys = new String[] { "nickname", "location","remark"};
	private int[] friendsItemIds = new int[] { R.id.myfriendlistitem_nickname, R.id.myfriendlistitem_loc,R.id.friend_remark };
	private Map<String, String> friendsPics = new HashMap<String, String>();
	private Map<Integer, Integer> friendMap = new HashMap<Integer, Integer>();
	private AsynImageLoader imageLoader = new AsynImageLoader();
	private Set<String> friendSet = new HashSet<String>();
	private int[] friendIds;   
	private boolean loadData = true;
	private int ring_id;
	private Button saveButton;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case FRIENDLIST_LOADING:
				mFriendsAdapter = null;
				thread = new Thread(new Runnable() {
					public void run() {
						initFriendsList();
						mFriendsAdapter = new SimpleAdapter(CircleInviteFriendsActivity.this, mFriendsItems, R.layout.view_myfriends_listitem, friendsItemKeys, friendsItemIds);
						mHandler.sendEmptyMessage(FRIENDLIST_LONDED);
					}

				});
				thread.start();
				break;

			case FRIENDLIST_LONDED:
				if (mFriendsAdapter != null && mFriendsItems.size()>0) {
					mFriendsList.setAdapter(mFriendsAdapter);
					bindItemClick();
				}
				break;
			}
		};
	};

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_friends_mygroup_myfriends);
		
		mFriendsList = (ListView)findViewById(R.id.friends_myfriends_listview);
		Intent intent = getIntent();
		ring_id = intent.getIntExtra("ring_id", -1);
		friendIds = intent.getIntArrayExtra("friendIds");
		
		if(friendIds != null && friendIds.length>0){
			for(int i=0;i<friendIds.length; i++){
				friendSet.add(String.valueOf(friendIds[i]));
			}
		}
		
		saveButton = (Button)findViewById(R.id.friends_save_button);
		Button gobackButton = (Button)findViewById(R.id.goback_myfriends_Button);
		saveButton.setOnClickListener(clickListener);
		gobackButton.setOnClickListener(clickListener);
		mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
	}

public OnClickListener clickListener = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.friends_save_button:
				if(friendSet.isEmpty()){
					Toast.makeText(CircleInviteFriendsActivity.this, getString(R.string.circle_invite_zero), Toast.LENGTH_LONG).show();
					return ;
				}
				int status = saveGroupsFriends();
				if(status != 1){
					Toast.makeText(CircleInviteFriendsActivity.this, getString(R.string.circle_fail), Toast.LENGTH_LONG).show();
				}else{
					Intent intent = new Intent(CircleInviteFriendsActivity.this,FriendsGroupDetailActivity.class);
					intent.putExtra("status", status);
					setResult(RESULT_OK, intent);
					finish();
				}
				break;
			case R.id.goback_myfriends_Button:
				NavUtils.navigateUpTo(CircleInviteFriendsActivity.this, new Intent(CircleInviteFriendsActivity.this,MyCirclesDetailActivity.class));
				break;
			default:
				break;
			}
		}
	};
	
	public void bindItemClick(){
		mFriendsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				// TODO Auto-generated method stub
				View view = mFriendsList.getChildAt(position);
				ImageView imageView = (ImageView)view.findViewById(R.id.friend_choose_imageview);
				if(imageView.getVisibility() == View.VISIBLE){
					imageView.setVisibility(View.INVISIBLE);
					friendSet.remove(String.valueOf(friendMap.get(position)));
				}else {
					imageView.setVisibility(View.VISIBLE);
					friendSet.add(String.valueOf(friendMap.get(position)));
				}
			}
		});
		
		mFriendsList.setOnScrollListener(scrollListener);
	}
	
	public OnScrollListener scrollListener = new OnScrollListener() {
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			LoadAdapterItemView();
			
		
		}
	};
	
	public int saveGroupsFriends(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int status = -1;
		try {
			jsonData.put(Constant.PARAM_RING_ID, ring_id);
			JSONArray jarray = new JSONArray();
			Iterator iterator = friendSet.iterator();
			while(iterator.hasNext()){
				jarray.put(iterator.next());
			}
			jsonData.put("ring_user_list", jarray);
			
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETCIRCLEFRIENDS , jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		
		return status;
	}
	
	public void LoadAdapterItemView(){
		int count = mFriendsList.getChildCount();
		for(int i=0; i<count; i++){
			View view = mFriendsList.getChildAt(i);
			ImageView chooseImage = (ImageView)view.findViewById(R.id.friend_choose_imageview);
			ImageView avarImageView = (ImageView)view.findViewById(R.id.myfriendlistitem_avatar);
			String picurl = friendsPics.get(String.valueOf(i));
			if(picurl != null && picurl != ""){
				Log.d("picurl", picurl);
				imageLoader.showImageAsyn(avarImageView, Constant.URL_USER_MIDDLE + picurl, R.drawable.glm_white);
			}
			int friId = friendMap.get(i);
			if(loadData && friendIds != null){
				int length = friendIds.length; 
				for(int j=0; j< length; j++){
					if(friendIds[j] == friId){
						chooseImage.setVisibility(View.VISIBLE);
						break;
					}
				}
			}
			if(i== count-1){
				loadData = false;
			}
			
		}
	}
	
	public void initFriendsList() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			int userId = UserInfoDAO.getUserInfo(CircleInviteFriendsActivity.this).getUserId();
			jsonData.put(Constant.PARAM_USERID_ONE, userId);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDLIST, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_CIRCLE_MYFRIENDS);

					initFriendItemFromJson(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	
	
	public void initFriendItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("nickname", entity.getUd_nickname());
			item.put("location", entity.getLoc_name());
			item.put("remark", entity.getUd_relname());
			Log.d("CircleFriends", entity.getUd_nickname() + ">>" + entity.getLoc_name() + ">>" + entity.getUd_relname());
			mFriendsItems.add(item);
			friendsPics.put(String.valueOf(i), entity.getUser_avatar());
			friendMap.put(i, entity.getUser_id());
		}
	}
	
}
